
package es.upm.dit.gsi.opactv.searchengines;

import es.upm.dit.gsi.opactv.util.Connection;
import es.upm.dit.gsi.opactv.util.FormatData;
import es.upm.dit.gsi.opactv.Book;
import java.net.URLEncoder;
import java.util.ArrayList;

public class LibraryThing implements SearchEngine {

    private Connection conn = new Connection();
    private FormatData fd = new FormatData();

    public LibraryThing() {
        // COLLECTION!
    }

    public void set(String title, String author, String tags) {
        // NADA
    }

    public ArrayList<Book> getBooks() {
        return new ArrayList();
    }

    public void completeBook(Book book) {
        String thisTitle = cleanAccents(book.getTitle());
        String thisAuthor = cleanAccents(book.getAuthor());
        String description = book.getDescription();
        if (description==null || description.equals("")) {
            description = getDescription(thisTitle, thisAuthor);
            book.addDescription(description);
        }
        if (description!=null) {
            for (String tag : getTags(thisTitle, thisAuthor)) book.addTag(tag);
            String cover = book.getCover();
            if (cover==null || cover.equals("")) {
                book.addCover(getCover(thisTitle, thisAuthor));
            }
        }
    }

    private String getDescription(String title, String author) {
        String description = "";
        String url = "http://www.librarything.com/title/" + urlEncoder(title);
        String data = conn.get(url);
        if (data.indexOf("Search LibraryThing")!=-1) return description;
        String container = fd.format(data, "og:title", "/>");
        String thisAuthor = cleanAccents(fd.format(container, " by ", "\"").trim());
        if (thisAuthor.indexOf(author)!=-1) {
            container = fd.format(data, "og:url", "/>");
            url = fd.format(container, "content=\"", "\"") + "/descriptions";
            data = conn.get(url);
            container = fd.format(data, "fwikiAtomicValue", "/div>");
            description = fd.format(container, ">", "<");
        } else return null;
        return description;
    }

    private ArrayList<String> getTags(String title, String author) {
        ArrayList<String> tags = new ArrayList();
        String url = "http://www.librarything.com/title/" + 
                     cleanAccents(urlEncoder(title));
        String data = conn.get(url);
        if (data.indexOf("Search LibraryThing")!=-1) return tags;
        String container = fd.format(data, "og:title", "/>");
        String thisAuthor = cleanAccents(fd.format(container, " by ", "\"").trim());
        if (thisAuthor.indexOf(author)!=-1) {
            container = fd.format(data, "og:url", "/>");
            url = fd.format(container, "content=\"", "\"");
            data = conn.get(url);
            int index;
            ArrayList<String[]> allTags = new ArrayList();
            while ((index = data.indexOf("class=\"tag\""))!=-1) {
                String[] tag = new String[2];
                tag[0] = fd.format(data, "_top\">", "</a>").trim();
                container = fd.format(data, "count\">", "</span>");
                tag[1] = fd.format(container, "(", ")").trim();
                tag[1] = tag[1].replaceAll(",", "");
                allTags.add(tag);
                data = data.substring(index+1);
            }
            String[][] tagsList = new String[5][2];
            for (int i=0; i<tagsList.length; i++) tagsList[i][1] = "0";
            for (String[] thisTag : allTags) {
                int thisTagCount = Integer.valueOf(thisTag[1]);
                for (int i=0; i<tagsList.length; i++) {
                    String[] tag = tagsList[i];
                    int tagCount = Integer.valueOf(tag[1]);
                    if (thisTagCount>tagCount) {
                        for (int j=tagsList.length-2; j>=i; j--) {
                            tagsList[j+1] = tagsList[j];
                        }
                        tagsList[i] = thisTag;
                        break;
                    }
                }
            }
            for (int i=0; i<tagsList.length; i++) tags.add(tagsList[i][0]);
        }
        return tags;
    }

    private String getCover(String title, String author) {
        String cover = "";
        String url = "http://www.librarything.com/title/" +
                      cleanAccents(urlEncoder(title));
        String data = conn.get(url);
        if (data.indexOf("Search LibraryThing")!=-1) return cover;
        String container = fd.format(data, "og:title", "/>");
        String thisAuthor = cleanAccents(fd.format(container, " by ", "\"").trim());
        if (thisAuthor.indexOf(author)!=-1) {
            container = fd.format(data, "og:image", "/>");
            cover = fd.format(container, "content=\"", "\"").trim();
        }
        return cover;
    }

    private String cleanAccents(String data) {
        data = data.replaceAll("á", "a");
        data = data.replaceAll("é", "e");
        data = data.replaceAll("í", "i");
        data = data.replaceAll("ó", "o");
        data = data.replaceAll("ú", "u");
        return data;
    }

    private String urlEncoder(String params) {
        String encoded = "";
        try {
            encoded = URLEncoder.encode(params, "UTF-8");
        } catch (Exception ex) {
            // System.err.println(ex);
        } finally {
            return encoded;
        }
    }

}
